import numpy as np
import pandas as pd
from datetime import datetime

from tensorflow import keras

import re
import json


num_keywords = ['all_type', 'android_wear', 'communication', 'entertainment', 'finance', 'food_drink', 'games',
                    'music_audio', 'news_magazines', 'productivity', 'shopping', 'tools', 'video_players_editors']


num_time_intervals = 28

num_time_diffs = 112

keyword_to_index = {keyword: index for index, keyword in enumerate(num_keywords)}


# 加载保存的模型
loaded_model = keras.models.load_model("static/model_03")

def process_model(data):
    """
    模型结果预测
    :param data: JSON 字符串
    :return:
    """

    # 初始化三维数组
    data_tensor = np.zeros((len(num_keywords), num_time_diffs, num_time_intervals))

    data = json.loads(data)

    submit_time = data['submit_time']
    submit_time = datetime.strptime(submit_time, "%Y-%m-%d %H:%M:%S")

    f_scrapy_data = data['f_scrapy_data']
    f_scrapy_data = json.loads(f_scrapy_data)

    for app in f_scrapy_data:

        date_list = f_scrapy_data[app]

        for d in date_list:

            app_time = datetime.strptime(d, "%Y-%m-%d %H:%M:%S")

            time_diff = (submit_time - app_time).days

            time_diff = int(time_diff / 3)

            if 0 <= time_diff < num_time_diffs:
                hour = app_time.hour

                if app in num_keywords:
                    keyword_index = keyword_to_index[app]

                    data_tensor[
                        keyword_index, time_diff, num_time_intervals - hour - 5] += 1

                # 如果时间大于 20点，更新后一天数据
                if hour >= 20:

                    if app in num_keywords and time_diff < num_time_diffs - 1:
                        keyword_index = keyword_to_index[app]

                        data_tensor[
                            keyword_index, time_diff + 1, 24 + num_time_intervals - hour - 5] += 1


    # 使用加载的模型进行预测
    input_data = np.array([data_tensor])
    return loaded_model.predict(input_data)[0][0]


